package com.elecbook.media.api.service.data;

import com.elecbook.media.model.po.UploadFile;
import com.elecbook.media.model.po.UploadImage;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

@Service
public class MongoDbServiceImpl implements MongoDbService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public UploadFile uploadFile(UploadFile uploadFile) {
        return mongoTemplate.save(uploadFile);
    }

    public UploadFile getUploadFileEntity(MultipartFile file) throws IOException {
        // 赋值上传图片的属性
        String fileName = file.getOriginalFilename();
        UploadFile uploadFile = new UploadFile()
                .setName(fileName)
                .setCreatedTime(LocalDateTime.now())
                .setContent(new Binary(file.getBytes()))
                .setContentType(file.getContentType())
                .setSize(file.getSize());
        return uploadFile;
    }

    @Override
    public UploadImage getUploadImageEntity(MultipartFile file) throws IOException {

        // 赋值上传图片的属性
        String fileName = file.getOriginalFilename();
        UploadImage uploadImage = new UploadImage()
                .setName(fileName)
                .setCreatedTime(LocalDateTime.now())
                .setContent(new Binary(file.getBytes()))
                .setContentType(file.getContentType())
                .setSize(file.getSize());
        return uploadImage;
    }

    @Override
    public UploadImage uploadImage(UploadImage uploadImage) {
        return mongoTemplate.save(uploadImage);
    }
}
